package com.sgj.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * @author 沈国纪
 * @date 2021/3/28 20:11
 * 异常捕获
 */

// 捕获所有添加了 controller 注解的页面异常
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

	/**
	 * 异常捕获
	 * @param request
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler({Exception.class})
	public ModelAndView handleException(HttpServletRequest request, Exception e) throws Exception {
		log.error("Request URL : {} , Exception : {}", request.getRequestURL(), e);
		if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
			throw e;
		}
		ModelAndView mav = new ModelAndView();
		mav.addObject("url", request.getRequestURL());
		mav.addObject("exception", e);
		mav.setViewName("error/error");
		return mav;
	}
}